import axios from 'axios'
import to from 'await-to-js'
import store from '@/store'
import router from '@/router'
import { refreshTokenAPI } from '@/api/user'

const instance = axios.create({
  baseURL: 'http://101.35.25.8:8000/v1_0/',
  timeout: 5000
})

// 请求拦截器 每次请求都会拦截到
instance.interceptors.request.use((config) => {
  config.cancelToken = new axios.CancelToken((cancel) => {
    store.commit('user/pushCancelFn', {
      cancelToken: cancel
    })
  })
  const token = store.state.user.token
  if (token) config.headers.Authorization = 'Bearer ' + token
  return config
}, err => Promise.reject(err))

// 响应拦截器 每次返回都会拦截到
instance.interceptors.response.use(res => {
  return res.data
}, async err => {
  // 鉴权失败 Token失效
  if (err.response && err.response.status === 401) {
    console.log(99999999)
    const [err2, data] = await to(refreshTokenAPI(store.state.user.refreshToken))
    if (err2) {
      // 1. 清空
      // RefreshToken
      store.commit('user/setToken', '')
      store.commit('user/setRefreshToken', '')
      router.push('/login?returnUrl=' + router.currentRoute.fullPath)
      // 2.跳转到登录页面
    } else {
      store.commit('user/setToken', data.data.data.token)
      // 重新执行 请求数据
      return instance(err.config)
    }
  }

  return Promise.reject(err)
})

export default ({ url, method = 'get', params, headers, data }) => {
  const promise = instance({
    url,
    method,
    params,
    data,
    headers
  })

  return to(promise)
}
